package com.atguigu.gulimall.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gulimall.feign.order.OrderFeignClient;
import com.atguigu.gulimall.order.entity.OrderInfo;
import com.atguigu.gulimall.pay.config.properties.AlipayProperties;
import com.atguigu.gulimall.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nicc
 * @version 1.0
 * @className PayServiceImpl
 * @date 2022-10-25 10:30
 */
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    AlipayClient alipayClient;
    @Autowired
    AlipayProperties alipayProperties;

    @Autowired
    OrderFeignClient orderFeignClient;

    @Override
    public String generateOrderPayPage(Long orderId) throws AlipayApiException {
        //1、创建一个 AlipayClient； 直接自动注入

        //2、创建一个支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        //3、拿到订单信息； 开启userauth的feign拦截器。保证登录的用户信息在调用的时候传下去
        Result<OrderInfo> infoData = orderFeignClient.getOrderInfoData(orderId);
        OrderInfo info = infoData.getData();

        //4、设置此次交易的内容 到底传哪些：https://opendocs.alipay.com/open/028r8t?scene=22
        Map<String,Object> bizContent = new HashMap<>();
        //商家的订单号
        bizContent.put("out_trade_no",info.getOutTradeNo());
        //订单金额
        bizContent.put("total_amount",info.getTotalAmount());
        //订单标题
        bizContent.put("subject",info.getTradeBody());
        //销售产品码, 使用固定值
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
//        bizContent.put("business_params","{}");//这个里面所有东西，支付宝会异步通知的时候继续给我们返回


        String formatDate = DateUtil.formatDate(info.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
        //自动收单 绝对过期时间
        bizContent.put("time_expire",formatDate);

        alipayRequest.setBizContent(Jsons.toStr(bizContent));

        //5、执行支付请求，得到二维码页面
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }
}
